package flc.ast.fragment;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.blankj.utilcode.util.TimeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.contrarywind.adapter.WheelAdapter;
import com.contrarywind.listener.OnItemSelectedListener;
import com.contrarywind.view.WheelView;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import flc.ast.R;
import flc.ast.activity.AddOvertimeActivity;
import flc.ast.adapter.OvertimeChildAdapter;
import flc.ast.adapter.OvertimeRecordAdapter;
import flc.ast.bean.OvertimeBean;
import flc.ast.bean.OvertimeRecordBean;
import flc.ast.databinding.FragmentHomeBinding;
import flc.ast.utils.MyDatabase;
import flc.ast.utils.MyRecordLoader;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> {

    private Dialog mySelMonthDialog;
    private WheelView wheelView1, wheelView2;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
    private int year, month;
    private OvertimeRecordAdapter overtimeRecordAdapter;
    private String formatStr = "%.1f";


    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.tvDate.setOnClickListener(this);
        mDataBinding.ivAdd.setOnClickListener(this);
        mDataBinding.ivLast.setOnClickListener(this);
        mDataBinding.ivNext.setOnClickListener(this);

        mDataBinding.rvOvertimeList.setLayoutManager(new LinearLayoutManager(mContext));
        overtimeRecordAdapter = new OvertimeRecordAdapter();
        mDataBinding.rvOvertimeList.setAdapter(overtimeRecordAdapter);
        overtimeRecordAdapter.setOnItemClickListener(this);

        //选择月份弹框
        selMonthDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivLast://上一月
                if (month == 1) {
                    month = 12;
                    year--;
                } else {
                    month--;
                }
                if (month < 10) {
                    mDataBinding.tvDate.setText(year + ".0" + month);
                } else {
                    mDataBinding.tvDate.setText(year + "." + month);
                }
                getData();
                break;
            case R.id.ivNext://下一月
                if (month == 12) {
                    month = 1;
                    year++;
                } else {
                    month++;
                }
                if (month < 10) {
                    mDataBinding.tvDate.setText(year + ".0" + month);
                } else {
                    mDataBinding.tvDate.setText(year + "." + month);
                }
                getData();
                break;
            case R.id.tvDate://月份
                mySelMonthDialog.show();
                break;
            case R.id.ivAdd://添加
                AddOvertimeActivity.overtimeBean = null;
                startActivity(AddOvertimeActivity.class);
                break;
            //选择日期弹框
            case R.id.ivDialogSelMonthCancel://取消
                mySelMonthDialog.dismiss();
                break;
            case R.id.ivDialogSelMonthRight://确定
                mySelMonthDialog.dismiss();
                int y = wheelView1.getCurrentItem() + 1980;
                int moon = wheelView2.getCurrentItem() + 1;
                String selDate = y + "-" + (moon < 10 ? "0" + moon : moon);
                year = y;
                month = moon;
                mDataBinding.tvDate.setText(selDate);
                getData();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        OvertimeChildAdapter overtimeChildAdapter = (OvertimeChildAdapter) adapter;
        OvertimeBean item = overtimeChildAdapter.getItem(position);
        AddOvertimeActivity.overtimeBean = item;
        startActivity(AddOvertimeActivity.class);
    }

    @Override
    protected void initData() {
        mDataBinding.tvDate.setText(TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM")));
        year = Integer.parseInt(TimeUtils.getNowString(new SimpleDateFormat("yyyy")));//获取当前年份
        month = Integer.parseInt(TimeUtils.getNowString(new SimpleDateFormat("M")));//获取当前月份
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        String startDate = year + "." + month + ".01";
        String endDate = "";
        if (month == 12) {
            endDate = (year + 1) + ".01.01";
        } else {
            endDate = year + "." + (month + 1) + ".01";
        }
        long startTime = TimeUtils.string2Millis(startDate, new SimpleDateFormat("yyyy.MM.dd"));
        long endTime = TimeUtils.string2Millis(endDate, new SimpleDateFormat("yyyy.MM.dd"));
        //每月加班
        double duration = 0;
        double income = 0;
        List<OvertimeBean> monthTime = MyDatabase.getInstance(mContext).getOvertimeDao().getMonthOvertime(startTime, endTime);

        if (monthTime.size() == 0) {
            mDataBinding.tvIncome.setText("0");
            mDataBinding.tvOvertimeHours.setText("0");
            mDataBinding.tvWorkTimeIncome.setText("0");
            mDataBinding.tvRecordDays.setText("0");
            mDataBinding.rvOvertimeList.setVisibility(View.GONE);
        } else {
            for (OvertimeBean overtimeBean : monthTime) {
                duration += overtimeBean.getDuration();
                income += overtimeBean.getIncome();
            }
            mDataBinding.tvIncome.setText(String.format(formatStr, income));
            mDataBinding.tvOvertimeHours.setText(String.format(formatStr, duration));
            mDataBinding.tvWorkTimeIncome.setText(String.format(formatStr, income));
            List<OvertimeRecordBean> list = MyRecordLoader.getInstance().loadData(true, monthTime);
            mDataBinding.tvRecordDays.setText(String.valueOf(list.size()));
            overtimeRecordAdapter.setList(list);
            mDataBinding.rvOvertimeList.setVisibility(View.VISIBLE);
        }
    }

    //选择月份弹框
    private void selMonthDialog() {
        mySelMonthDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_month, null);
        mySelMonthDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mySelMonthDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lp.width = (int) (dm.widthPixels * 1);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView dialogCancel = inflate.findViewById(R.id.ivDialogSelMonthCancel);
        ImageView dialogRight = inflate.findViewById(R.id.ivDialogSelMonthRight);
        wheelView1 = inflate.findViewById(R.id.wheel_view1);
        wheelView2 = inflate.findViewById(R.id.wheel_view2);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
        wheelView1.setDividerColor(Color.parseColor("#2E979797"));
        wheelView1.setTextColorCenter(Color.parseColor("#000000"));
        wheelView1.setLineSpacingMultiplier(2.5f);
        wheelView1.setDividerType(WheelView.DividerType.WRAP);
        wheelView1.setCurrentItem(43);
        wheelView1.setItemsVisibleCount(5);
        wheelView1.setCyclic(true);
        wheelView1.setTextSize(15);
        wheelView2.setDividerColor(Color.parseColor("#2E979797"));
        wheelView2.setTextColorCenter(Color.parseColor("#000000"));
        wheelView2.setLineSpacingMultiplier(2.5f);
        wheelView2.setDividerType(WheelView.DividerType.WRAP);
        wheelView2.setCurrentItem(0);
        wheelView2.setItemsVisibleCount(5);
        wheelView2.setCyclic(true);
        wheelView2.setTextSize(15);
        //设置滚轮数据
        List<String> listYear = new ArrayList<>();//年 1980-2040
        for (int i = 0; i < 61; i++) {
            listYear.add(String.valueOf(1980 + i));
        }
        List<String> listMonth = new ArrayList<>();//月 12
        for (int i = 0; i < 12; i++) {
            listMonth.add(String.valueOf((i + 1) < 10 ? "0" + (i + 1) : i + 1));
        }
        WheelAdapter adapter1 = new ArrayWheelAdapter(listYear);
        wheelView1.setAdapter(adapter1);
        WheelAdapter adapter2 = new ArrayWheelAdapter(listMonth);
        wheelView2.setAdapter(adapter2);

        //滚动到对应日期
        String date = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
        String[] split = date.split("-");
        int year = Integer.parseInt(split[0]);//年
        int moon = Integer.parseInt(split[1]);//月
        wheelView1.setCurrentItem(year - 1980);
        wheelView2.setCurrentItem(moon - 1);
    }

}